<template>
  <div class="container">
    <a-card class="general-card" :title="$route.meta.locale">
      <table-search
        v-permission="'blood-test:list:query'"
        :fileds="searchFileds"
        @search="search"
        @reset="search"
      ></table-search>
      <xTable
        v-model:refresh="refresh"
        v-model:selected-keys="selectedKeys"
        :params="params"
        :columns="tableColumns"
        :http="{
          list: getDataList,
          del: delById,
          batchDel: delByIds,
        }"
        :http-permission="{
          del: 'blood-test:list:del',
          batchDel: 'blood-test:list:batchDel',
        }"
        http-data-key="rows"
        row-key="id"
      >
        <template #operation-default>
          <div v-permission="'blood-test:list:add'" class="item">
            <a-button type="outline" @click="editOpen(null)"> 新增 </a-button>
          </div>
        </template>
        <template #sex="{ row }">
          <dict-tag :options="dict.sys_user_sex" :value="row.sex" />
        </template>
        <template #payType="{ row }">
          <dict-tag :options="dict.pay_type" :value="row.payType" />
        </template>
        <template #optional="{ row }">
          <router-link
            :to="{
              name: 'PatientDetail',
              params: { id: row.userId, name: row.nickName, tab: '4' },
            }"
          >
            <a-button type="text">查看</a-button>
          </router-link>
          <a-button
            v-permission="'blood-test:list:edit'"
            type="text"
            status="success"
            @click="editOpen(-1, row)"
          >
            编辑
          </a-button>
        </template>
      </xTable>
    </a-card>
    <!-- m-tag="a-drawer" -->
    <EditModal
      ref="edit"
      :default-value="defValue"
      width="750px"
      :fields="editFields"
      :http-add="addData"
      :http-edit="editData"
      :handler="handler"
      @reload="refresh = true"
    >
    </EditModal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { getDict } from '@/utils/dict';
  import {
    getDataList,
    addData,
    delById,
    delByIds,
    editData,
  } from '@/api/bloodTest';
  import { treeselect as deptTreeSelect } from '@/api/system/dept';
  import { queryPatient } from '@/api/common';
  import getPageConfig from './config';

  const dict = getDict('sys_user_sex', 'pay_type');
  const edit = ref();
  const deptTree = ref([]);
  const userList = ref([]);
  const pageConfig = getPageConfig({
    sys_user_sex: dict.sys_user_sex,
    deptTree,
    userList,
    pay_type: dict.pay_type,
  });
  const selectedKeys: any = ref([]);
  const searchFileds = reactive(pageConfig.searchFileds);
  const tableColumns = reactive(pageConfig.tableColumns);
  const editFields = reactive(pageConfig.editFields);
  const defValue = ref({});
  const refresh = ref(true);
  // 定义表格查询参数
  const params = ref({
    dateRange: [],
  });
  // 定义搜索方法
  const search = (data: any) => {
    params.value = data;
    refresh.value = true;
  };
  const editOpen = async (keys: any | any[], value?: any) => {
    if (value) {
      edit.value.show(value.userId, {
        ...value,
        pictureAddress: value?.pictureAddress?.split(',').map((item: any) => {
          const sp = item?.split('/');
          return {
            status: 'done',
            percent: 100,
            url: `${import.meta.env.VITE_API_BASE_URL}${item}`,
            name: sp[sp.length - 1],
            response: {
              fileName: item,
            },
          };
        }),
        formAddress: value?.formAddress?.split(',').map((item: any) => {
          const sp = item?.split('/');
          return {
            status: 'done',
            percent: 100,
            url: `${import.meta.env.VITE_API_BASE_URL}${item}`,
            name: sp[sp.length - 1],
            response: {
              fileName: item,
            },
          };
        }),
      });
    } else if (Array.isArray(keys) && keys.length === 1) {
      edit.value.show(keys[0]);
    } else if (!Array.isArray(keys)) {
      edit.value.show(keys);
    } else if (Array.isArray(keys) && keys.length < 1) {
      Message.warning('必须选中一条数据');
    } else if (Array.isArray(keys) && keys.length > 1) {
      Message.warning('只能选中一条数据');
    }
  };

  const handler = (data: any) => {
    // if (data.payType) {
    //   data.payType = data.payType.join(',');
    // }
    if (data.formAddress) {
      data.formAddress = data.formAddress
        .filter((item: { status: string }) => item.status === 'done')
        .map((item: { response: { fileName: any } }) => item.response.fileName)
        .join(',');
    }
    if (data.pictureAddress) {
      data.pictureAddress = data.pictureAddress
        .filter((item: { status: string }) => item.status === 'done')
        .map((item: { response: { fileName: any } }) => item.response.fileName)
        .join(',');
    }
    return {
      ...data,
    };
  };
  const initSelectData = async () => {
    const deptRes = await deptTreeSelect();
    if (deptRes.code !== 200) {
      Message.error(deptRes.msg);
      return;
    }
    deptTree.value = deptRes.data;
    const userRes = await queryPatient();
    if (userRes.code !== 200) {
      Message.error(userRes.msg);
      return;
    }
    userList.value = userRes.data.map(
      (item: { userId: any; nickName: any; idNumber: any }) => ({
        value: item.userId,
        label: `${item.nickName}-${item.idNumber}`,
      })
    );
  };
  initSelectData();
</script>

<style scoped lang="less">
  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
